package com.hitqz.robot.biz.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hitqz.robot.api.business.model.param.patrol.QueryPatrolCheckTypeParams;
import com.hitqz.robot.api.business.model.vo.patrol.PatrolCheckTypeVo;
import com.hitqz.robot.api.common.entity.PatrolCheckType;
import com.hitqz.robot.api.common.entity.Robot;
import com.hitqz.robot.api.common.entity.RobotConfig;
import com.hitqz.robot.biz.core.FileProperties;
import com.hitqz.robot.biz.service.PatrolCheckTypeService;
import com.hitqz.robot.biz.service.PatrolObjectService;
import com.hitqz.robot.biz.service.RobotConfigService;
import com.hitqz.robot.biz.service.RobotService;
import com.hitqz.robot.common.core.util.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Objects;

/**
 * @author wengyx
 * @date 2024/8/7
 */

@RestController
@AllArgsConstructor
@RequestMapping("/patrolCheckType")
@Slf4j
@Tag(name = "巡检项目类型管理")
public class PatrolCheckTypeController {

    private final PatrolCheckTypeService patrolCheckTypeService;
    private final PatrolObjectService patrolObjectService;
    private final FileProperties fileProperties;

    @PostMapping("/page")
    @Operation(summary = "分页查询巡检项目类型")
    public R<Page<PatrolCheckTypeVo>> page(@RequestBody QueryPatrolCheckTypeParams query) {
        Page<PatrolCheckType> page = new Page<>(query.getCurrent(),query.getSize());
        Page<PatrolCheckType> data = patrolCheckTypeService.page(page,
                Wrappers.<PatrolCheckType>lambdaQuery()
                        .like(StrUtil.isNotBlank(query.getName()), PatrolCheckType::getName,
                                query.getName())
                        .eq(query.getIsVision()!=null, PatrolCheckType::getIsVision,
                                query.getIsVision())
                        .orderByDesc(PatrolCheckType::getId));
        Page<PatrolCheckTypeVo> voPage = new Page<>();
        BeanUtil.copyProperties(data,voPage);//复制页码等信息
        List<PatrolCheckTypeVo> voList = BeanUtil.copyToList(data.getRecords(), PatrolCheckTypeVo.class);//一些实体类的get/set方法没有调用到，需要单独复制一下
        voPage.setRecords(voList);
        return R.ok(voPage);
    }

    @GetMapping("/{id}" )
    @Operation(summary = "根据id查询巡检项目类型")
    public R<PatrolCheckTypeVo> getById(@PathVariable("id") Integer id) {
        PatrolCheckType patrolCheckType = patrolCheckTypeService.getById(id);
        PatrolCheckTypeVo vo = new PatrolCheckTypeVo();
        BeanUtil.copyProperties(patrolCheckType,vo,false);
        return R.ok(vo);
    }

    @PostMapping
    @Operation(summary = "新增巡检项目类型")
    public R save(@RequestBody @Validated PatrolCheckType dto) {
        return R.ok(patrolCheckTypeService.save(dto));
    }

    @PutMapping
    @Operation(summary = "修改巡检项目类型")
    public R updateById(@RequestBody @Validated PatrolCheckType dto) {
        return R.ok(patrolCheckTypeService.updateById(dto));
    }

    @DeleteMapping
    @Operation(summary = "根据id删除巡检项目类型")
    public R removeById(@RequestBody Integer[] ids) {
        patrolObjectService.removeSelfAndStandardBatchByCheckTypeIds(ids);
        return R.ok(patrolCheckTypeService.removeBatchByIds(CollUtil.toList(ids)));
    }



    @PostMapping("/{id}/testByFile" )
    @Parameter(name = "file", required = true)
    @Operation(summary = "测试视觉检测项-上传图片")
    public R<String> test(@PathVariable("id") Integer id,@RequestPart("file") MultipartFile file) {
        if(file.isEmpty()) {
            return R.failed("请上传文件");
        }
        String dir =fileProperties.getLocal().getBasePath();
        if (StrUtil.isEmpty(dir)) {
            return R.failed("未进行配置上传目录");
        }
        boolean isMediaFile = file.getOriginalFilename().contains("mp4")
                || file.getOriginalFilename().contains("jpg")
                || file.getOriginalFilename().contains("jpeg")
                || file.getOriginalFilename().contains("wav")
                || file.getOriginalFilename().contains("m4a");
        if (!isMediaFile) {
            return R.failed("文件格式不支持");
        }
        String path = "";
        try{
            path = fileProperties.getLocal().getBasePath() + File.separator + "temp" + File.separator + file.getOriginalFilename();
            FileUtil.writeFromStream(file.getInputStream(),path);
        }catch (Exception e){
            log.warn("下载文件失败");
            return R.failed("文件传输失败");
        }
        return patrolCheckTypeService.detectByFile(id,path);
    }


    @GetMapping("/{id}/testByEquipment" )
    @Operation(summary = "测试检测项-使用设备")
    public R<String> test(@PathVariable("id") Integer id, @RequestParam(value = "equipmentId") Integer equipmentId) {
        log.info("id:{},equipmentId:{}",id,equipmentId);
        return patrolCheckTypeService.detectByEquipment(id,equipmentId);
    }



}
